package com.xuxueli.applyModules.listener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.xuxueli.applyModules.exception.ExceptionCustom;
import com.xuxueli.applyModules.entity.GraduaterName;
import com.xuxueli.applyModules.entity.GraduaterNamePara;

import java.util.ArrayList;
import java.util.List;

/*
 * 监听器批处理数据
 * */
public class BasicExcelListener extends AnalysisEventListener<GraduaterNamePara> {

    /**
     * 批处理阈值2000
     */
    private static final int BATCH_COUNT = 2000;
    List<GraduaterNamePara> list = new ArrayList<GraduaterNamePara>();
    List<GraduaterName> finalList = new ArrayList<GraduaterName>();

    @Override
    public void invoke(GraduaterNamePara basic, AnalysisContext analysisContext) {
        try {
            //通用方法数据校验
            ExcelImportValid.valid(basic);
        }catch (ExceptionCustom e){
            // System.out.println(e.getMessage());
            //在easyExcel监听器中抛出业务异常 这个异常会被controller捕获，将错误信息返回给前端
            throw new ExcelAnalysisException(e.getMessage());
        }
        //获取对应的行数
        int num = analysisContext.readRowHolder().getRowIndex();
        basic.setRowNum(num + 1);
        list.add(basic);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        //调用saveData()方法
//        GraduaterNameService graduaterNameService = SpringUtil.getBean(GraduaterNameService.class);
//
//        if(CollectionUtils.isNotEmpty(list)){
//            for (GraduaterNamePara graduaterNamePara:list) {
//                GraduaterName graduaterName = new GraduaterName();
//                BeanUtils.copyProperties(graduaterNamePara,graduaterName);
//                finalList.add(graduaterName);
//            }
//        }
//        if(CollectionUtils.isNotEmpty(finalList)){
//            graduaterNameService.insertBatch(finalList,1000);
//            finalList.clear();
//        }

    }
}
